package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.R;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.ParticipantMapper;
import com.ruan.mapper.ProjectMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.ParticipantExt;
import com.ruan.pojoExt.TaskExt;
import com.ruan.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/tasks")
public class TasksController {
    @Autowired
    private TasksService tasksService;
    @Autowired
    private ProjectService projectsService;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ProjectService peojectService;
    @Autowired
    private ProjectAssignmentsService projectAssignmentsService;
    @Autowired
    private ParticipantMapper participantMapper;
    @Autowired
    PositionService positionService;

    @PostMapping("/page/{currentPage}/{pageSize}")
    public R<Page> page(@PathVariable int currentPage,
                        @PathVariable int pageSize,
                        @RequestBody QueryEmployeeCondition queryEmployeeCondition){//第三个参数 name 可能是从前端的用户输入或者页面的搜索框中获取的
//        System.out.println("task的page传来的参数是："
//                +currentPage+pageSize+queryEmployeeCondition);
        Page<Tasks> iPage=new Page<>(currentPage,pageSize);
        Page<TaskExt> iPageExt = new Page<>();
        //根据任务名模糊搜索
        LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(!queryEmployeeCondition.getTaskName().equals(""),
                Tasks::getTaskName,queryEmployeeCondition.getTaskName());

        //根据组员名模糊搜索
        LambdaQueryWrapper<Employee> employeeWrapper =new LambdaQueryWrapper<>();
        employeeWrapper.like(Employee::getName,queryEmployeeCondition.getName());//模糊查询
        List<Employee> employeeList = employeeMapper.selectList(employeeWrapper);
        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
        queryWrapper.in(Tasks::getEmployeeId, employeeIds);

//        queryWrapper.like(queryEmployeeCondition.getName()!=null,
//                Tasks::getTaskName,queryEmployeeCondition.getName());

        //根据任务完成状态搜索
        queryWrapper.like(queryEmployeeCondition.getStatus()!=null,
                Tasks::getCompletionStatus,queryEmployeeCondition.getStatus());

        //小组长用自己的employeeId查自己分配给组员的任务
        LambdaQueryWrapper<Project> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.eq(queryEmployeeCondition.getId()!=null,
                Project::getEmployeeId,queryEmployeeCondition.getId());
        //每个人可以安排多个项目
        List<Project> projectList = projectMapper.selectList(queryWrapper1);
        List<Long> projectIds =
                projectList.stream().map(Project::getId).collect(Collectors.toList());

        queryWrapper.in(Tasks::getProjectId, projectIds);//每个人可能有多个项目，可能已做完或者未做完

//        queryWrapper.orderByDesc(Tasks::getCreateTime);

        tasksService.page(iPage,queryWrapper);

        BeanUtils.copyProperties(iPage,iPageExt,"records");
        //处理
        List<Tasks> records = iPage.getRecords();
        List<TaskExt> list = records.stream().map((item) -> {//item:遍历出来的每一个菜品对象
            TaskExt taskExt = new TaskExt();//只有DishDto符合菜品管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,taskExt);//填充入dish的普通属性
//获取搜索第一个属性所要用到的id => projectName
            Long projectId = item.getProjectId();//拿到了每个任务所对应的项目id
            //根据projectId查项目负责人
            Project projects = projectsService.getById(projectId);
//获取搜索第二个属性所要用到的id => enamer
            Long employerId = projects.getEmployeeId();//拿到了每个任务所对应的分配表里的项目小组长的id
            Employee employer = employeeService.getById(employerId);
//获取搜索第三个属性所要用到的id => ename
            Long employeeId = item.getEmployeeId();//拿到了每个任务所对应的分配表里的项目小组长的id
            //根据employeeId查任务负责人
            Employee employee = employeeService.getById(employeeId);
//            Long createUserId = item.getCreateUser();
//            Long updateUserId = item.getUpdateUser();
//            Employee createdUser = employeeService.getById(queryEmployeeCondition.getId());
//            Employee updatedUser = employeeService.getById(updateUserId);
            if(projects != null){//能查到对应的项目
                String projectName = projects.getProjectName();
                taskExt.setProjectName(projectName);//填充入tasks没有的projectName属性
            }
            if(employer != null){//能查到项目负责人
                String enamer = employer.getName();
                taskExt.setEmployerName(enamer);
            }
            if(employee != null){//能查到任务负责人
                String ename = employee.getName();
                taskExt.setEmployeeName(ename);
            }
//            taskExt.setCreatedUser(createdUser.getName());
//            taskExt.setUpdatedUser(updatedUser.getName());
            return taskExt;
        }).collect(Collectors.toList());//就转成集合了，赋给List<TaskExt> list
//        System.out.println("list有了什么"+list);
        iPageExt.setRecords(list);//list获得了改造过后的taskExt集合之后，被用来设置page对象的Records属性

        return R.success(iPageExt);//可以多展示几个属性
    }

    @GetMapping("/getParticipantList")
    public Result getParticipantList(@RequestParam String projectId){
//        System.out.println("getParticipantList的参数是"+projectId);
        LambdaQueryWrapper<Participant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Participant::getProjectId,projectId);
        List<Participant> participantList = participantMapper.selectList(queryWrapper);
//        System.out.println("该负责人负责的项目的participantList参与人员id有："+participantList);
        if(participantList!=null){
            List<ParticipantExt> participantExtList = new ArrayList<>();
            for(Participant participant : participantList){
                ParticipantExt participantExt = new ParticipantExt();
                Project project = peojectService.getById(participant.getProjectId());

                //已离职..的选不中
                LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Employee::getId,participant.getEmployeeId());
                queryWrapper1.notIn(Employee::getStatus,"离职","待审核");
                Employee employee = employeeMapper.selectOne(queryWrapper1);
//                Employee employee = employeeService.getById(participant.getEmployeeId());

                participantExt.setProjectName(project.getProjectName());
                if (employee != null) {
                    if(employee.getPositionId() != null){
                        Position position = positionService.getById(employee.getPositionId());
                        participantExt.setPositionName(position.getPname());
                    }
                    if (employee.getName() != null) {
                        participantExt.setEmployeeName(employee.getName());
                    }
                    //确定没有离职之后再进行基础属性搬迁
                    BeanUtils.copyProperties(participant,participantExt);
                    participantExtList.add(participantExt);
                }

            }
            return new Result(Code.SELECT_OK,participantExtList,"项目参与人员查询成功");
        }
        return new Result(Code.SELECT_ERR,"项目参与人员查询失败");
    }

    /**
     * 员工任务完成确认
     */
    @GetMapping("/approvalTask/{id}")
    public Result approvalTask(@PathVariable Integer id){
//        System.out.println("approvalTask传来的任务id是"+id);
        if (tasksService.approvalTask(id)){
            return new Result(Code.UPDATE_OK,"任务确认完成！");
        }
        return new Result(Code.UPDATE_ERR,"任务确认失败！");
    }

    @GetMapping("/checkTodayTasks")
    public Result checkTodayTasks(@RequestParam String employeeId) {
        List<TaskExt> taskExtList = tasksService.getTodayTasks(employeeId);
        if(taskExtList.isEmpty()){//isEmpty() ???
            return new Result(Code.SELECT_ERR,"今日任务查找失败");
        }
        return new Result(Code.SELECT_OK,taskExtList,"今日任务查找成功");

    }

    /**
     * 员工每日任务
     */
    @PostMapping("/dailyTask/{currentPage}/{pageSize}")
    public R<Page> getDailyTask(@PathVariable int currentPage,
                        @PathVariable int pageSize,
                        @RequestBody QueryEmployeeCondition queryEmployeeCondition){
        System.out.println("dailyTask传来的参数是："
                +currentPage+pageSize+queryEmployeeCondition);
        Page<Tasks> iPage=new Page<>(currentPage,pageSize);
        Page<TaskExt> iPageExt = new Page<>();

        LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper();
        //根据任务完成状态搜索
        queryWrapper.like(queryEmployeeCondition.getStatus()!=null,
                Tasks::getCompletionStatus,queryEmployeeCondition.getStatus());
        //固定查询各位组长分配给自己的任务
        queryWrapper.eq(Tasks::getEmployeeId,queryEmployeeCondition.getId());//前端应该传来个人的employeeId
        queryWrapper.orderByDesc(Tasks::getCreateTime);
        tasksService.page(iPage,queryWrapper);
        BeanUtils.copyProperties(iPage,iPageExt,"records");

        List<Tasks> records = iPage.getRecords();
        List<TaskExt> list = records.stream().map((item) -> {//item:遍历出来的每一个菜品对象
            TaskExt taskExt = new TaskExt();//只有DishDto符合菜品管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,taskExt);//填充入dish的普通属性
//获取搜索第一个属性所要用到的id => projectName
            Long projectId = item.getProjectId();//拿到了每个任务所对应的项目id
            //根据projectId查项目负责人
            Project projects = projectsService.getById(projectId);
//获取搜索第二个属性所要用到的id => enamer
            Long employerId = projects.getEmployeeId();//拿到了每个任务所对应的分配表里的项目小组长的id
            Employee employer = employeeService.getById(employerId);
//获取搜索第三个属性所要用到的id => ename
            Long employeeId = item.getEmployeeId();//拿到了每个任务所对应的分配表里的项目小组长的id
            //根据employeeId查任务负责人
            Employee employee = employeeService.getById(employeeId);
            if(projects != null){//能查到对应的项目
                String projectName = projects.getProjectName();
                taskExt.setProjectName(projectName);//填充入tasks没有的projectName属性
            }
            if(employer != null){//能查到项目负责人
                String enamer = employer.getName();
                taskExt.setEmployerName(enamer);
            }
            if(employee != null){//能查到任务负责人
                String ename = employee.getName();
                taskExt.setEmployeeName(ename);
            }
            // 获取当前系统时间
//            LocalDateTime currentTime = LocalDateTime.now();
//            LocalDateTime itemDeadline = item.getDeadline(); // 假设item是您的对象，包含了截止时间
//            Instant currentInstant = currentTime.atZone(ZoneId.systemDefault()).toInstant();
//            Instant deadlineInstant = itemDeadline.atZone(ZoneId.systemDefault()).toInstant();
//
//            if (currentInstant.isAfter(deadlineInstant)) {
//                //当前时间晚于截止时间//就默认不能完成
//                System.out.println("当前时间晚于截止时间");
//                item.setCompletionStatus(Tasks.CompletionStatus.incomplete);
//            }
            return taskExt;
        }).collect(Collectors.toList());//就转成集合了，赋给List<TaskExt> list
        System.out.println("list有了什么"+list);
        iPageExt.setRecords(list);//list获得了改造过后的taskExt集合之后，被用来设置page对象的Records属性

        return R.success(iPageExt);
    }

    @PutMapping("/updateTask")
    public Result update(@RequestBody Tasks tasks){
//‘@RequestBody’注释表明‘Tasks’对象将从请求体中反序列化，通常采用JSON或XML格式。
        log.info("修改任务信息：："+tasks.toString());

        long id = Thread.currentThread().getId();
        log.info("当前线程id为：{}",id);
        boolean a = tasksService.updateById(tasks);//updateById继承自父接口IService(由mybatis-plus提供)
        if(a){
            return new Result(Code.UPDATE_OK,"任务信息修改成功");
        }
        return new Result(Code.UPDATE_ERR,"任务修改失败");
    }
    //新增任务
    @PostMapping("/addTask")
    public Result save(@RequestBody Tasks tasks){
        log.info("新增任务，任务信息：{}",tasks.toString());
        boolean a = tasksService.save(tasks);//把这个对象存进去
//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
        if(a){
        return new Result(Code.SAVE_OK,"任务分配成功");
        }
        return new Result(Code.SAVE_ERR,"任务分配失败");
    }
}
